package com.sofwin.controller;

import com.github.pagehelper.PageInfo;
import com.sofwin.Constants;
import com.sofwin.ResponseEntity;
import com.sofwin.pojo.SysRole;
import com.sofwin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @packageName: com.sofwin.controller
 * @user: andyliu
 * @date: 2023/1/3 9:38
 * @email 115176513@qq.com
 * @description: TODO
 */
@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @GetMapping("")
    public String toList(){
        return "role/list";
    }
    @PostMapping("data")
    @ResponseBody
    public ResponseEntity data(SysRole role, @RequestParam(required = true,defaultValue = "1")
                               Integer pageNumber,
                               @RequestParam(required = true,defaultValue = Constants.PAGE_SIZE) Integer pageSize){
        PageInfo<SysRole> roles = roleService.queryByPage(role,pageNumber,pageSize);
        return ResponseEntity.success(roles);
    }
    @GetMapping("toAdd")
    public String toAdd(Integer id, Model model){
        if(id!=null){
            // 根据ID查询角色信息并放入到作用域中
            SysRole role = roleService.queryById(id);
            model.addAttribute("role",role);
        }
        return "role/edit";
    }
    @PostMapping("save")
    @ResponseBody
    public ResponseEntity save(SysRole role,Integer[] resourceIds){
        // 只保存了角色信息
        // 还需要保存当前角色的资源信息
        boolean status = roleService.saveOrUpdate(role,resourceIds);
        if(status){
            return ResponseEntity.success(status);
        }
        return ResponseEntity.error(status);
    }
    @DeleteMapping("delete/{id}")
    @ResponseBody
    public ResponseEntity delete(@PathVariable Integer id){
        boolean status = roleService.removeById(id);
        if(status){
            return ResponseEntity.success(status);
        }
        return ResponseEntity.error(status);
    }
    @DeleteMapping("delete")
    @ResponseBody
    public  ResponseEntity deletes(Integer[] ids){
        boolean status = roleService.removeByIds(ids);
        if(status){
            return ResponseEntity.success(status);
        }
        return ResponseEntity.error(status);
    }

    /**
     * 根据角色名称查询角色信息是否存在
     * @param roleName
     * @return
     */
    @GetMapping("queryRole")
    @ResponseBody
    public boolean queryRole(String roleName){
        boolean status = roleService.queryByName(roleName);
        return status;
    }
}
